package com.caijb.reactive;

import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;

/**
 * @author caijb
 * @version 1.0
 * @data 2025/11/8 00:07
 */
public class ReactiveStreamDemo {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName());
        // 发布者
        SubmissionPublisher<String> publisher = new SubmissionPublisher<>();
        // 订阅者
        Flow.Subscriber<String> subscriber = new Flow.Subscriber<>() {

            Flow.Subscription subscription;

            @Override
            public void onSubscribe(Flow.Subscription subscription) {
                this.subscription = subscription;
                subscription.request(1);
                System.out.println("订阅成功");
            }

            @Override
            public void onNext(String item) {
                System.out.println(Thread.currentThread().getName());
                System.out.println("接收到数据：" + item);
                subscription.request(10);
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println("发生错误：" + throwable.getMessage());
            }

            @Override
            public void onComplete() {
                System.out.println("数据接收完成");
            }
        };
        // 建立订阅关系
        publisher.subscribe(subscriber);
        for (int i = 0; i < 100; i++) {
            publisher.submit("数据" + i);
        }
        try {
            Thread.currentThread().join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
